<template>
  <div class="register-wrapper">
    <div class="form-box">

      <div class="form-title">
        <p>账号注册</p>
      </div>

      <el-form :model="registerForm" :rules="registerRules" ref="refForm" status-icon label-width="110px" class="registerForm">
        <el-form-item label="姓名" prop="userName">
          <el-input v-model="registerForm.userName" style="width: 150px" clearable placeholder="填写姓名"></el-input>
        </el-form-item>

        <el-form-item label="性别">
          <el-radio-group v-model="registerForm.sex" style="float: left;margin-top: 15px">
            <el-radio label='0'>男</el-radio>
            <el-radio label='1'>女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="电话号码" prop="telephone">
          <el-input v-model="registerForm.telephone" style="width: 180px" clearable placeholder="填写电话号码"></el-input>
        </el-form-item>

        <el-form-item label="详细地址" prop="city">
          <el-select v-model="registerForm.city" placeholder="所在城市">
            <el-option label="上海" value="上海"></el-option>
            <el-option label="北京" value="北京"></el-option>
            <el-option label="成都" value="成都"></el-option>
            <el-option label="重庆" value="重庆"></el-option>
            <el-option label="郑州" value="郑州"></el-option>
            <el-option label="武汉" value="武汉"></el-option>
            <el-option label="南京" value="南京"></el-option>
            <el-option label="杭州" value="杭州"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" style="width: 220px" clearable placeholder="注册邮箱"></el-input>
        </el-form-item>

        <el-form-item label="银行账号" prop="bankCount">
          <el-input v-model.number="registerForm.bankCount" style="width: 420px" clearable placeholder="绑定银行账号"></el-input>
        </el-form-item>

        <div class="el switch">
          <el-radio-group v-model="registerForm.identity">
            <el-radio :label='0'>个人用户</el-radio>
            <el-radio :label='1'>商家用户</el-radio>
            <el-radio :label='2'>配送员</el-radio>
          </el-radio-group>
        </div>

        <div v-if="registerForm.identity===1">
          <el-form-item label="营业执照编号" prop="account">
            <el-input v-model.number="registerForm.account" clearable placeholder="请输入营业执照编号" style="width: 420px"></el-input>
          </el-form-item>
        </div>

        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="registerForm.password" autocomplete="off" style="width: 420px" placeholder="设置密码"></el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="checkPassword">
          <el-input type="password" v-model="registerForm.checkPassword" autocomplete="off" style="width: 420px" placeholder="确定密码"></el-input>
        </el-form-item>

        <!--提交/重置按钮-->
        <el-form-item>
          <el-button :loading="loading" type="primary" @click="submitForm()">
            <span v-if="!loading">注 册</span>
            <span v-else>注 册 中...</span>
          </el-button>
          <el-button type="primary" @click="resetForm('refForm')">重 置</el-button>
          <el-button type="primary" plain @click="returnLogin()">返 回</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--
    背景图
    -->
    <div class="background" id="background"></div>
    <div class="yinghua" id="yinghua"></div>
    <canvas class="fireworks"
            style="position: fixed; left: 0; top: 0; z-index: 99999999; pointer-events: none;"></canvas>
  </div>

</template>
<script>
/**
 * 引入register.js中的register()方法
 */
import {register} from "@/api/register";
import $ from "jquery";
import {load2D_bg, load2D_bg2, load2D_bg2_2, load2D_yinghua} from "@/api/background";

export default {
  name: "Register",
  data() {
    /**
     * validatePass：密码框校验器
     */
    const validatePass = (rule, value, callback) => {
      console.log(value)
      if (value === '') {
        callback(new Error('请输入密码'));
      } else {
        /**
         * 一般来讲，获取DOM元素，需要使用document.querySelector('#input1')方法去获取dom节点，然后再获取input1的值。
         但是使用了ref绑定之后，我们就不需要再获取dom节点了，可以直接在上面的input上绑定input1，然后$refs里面调用就行。
         在JavaScript里面通过this.$refs.input1去调用，这样的做法实际上是访问VUE虚拟出来的DOM，可以有效减少获取/操作DOM节点的性能消耗。
         * <div id="app">
         <input type="text" ref="input1" />
         <button @click="add">添加</button>
         </div>
         * 这里的$refs可以看做是ref的选择器，这个$ref是一个对象，通过key可以获取到其中存放的对象。
         当然了，既然是对象，也可以使用方括号运算符去访问，具体是this.$refs[input1]。
         */
        if (this.registerForm.checkPassword !== '') {
          this.$refs.refForm.validateField('checkPassword');
        }
        callback();
      }
    };
    /**
     * validatePass2：确认密码框校验器
     */
    const validatePass2 = (rule, value, callback) => {
      console.log(value)
      console.log(this.registerForm.password)
      if (value === '') {
        callback(new Error('请再次输入密码'));
      } else if (value !== this.registerForm.password) {
        callback(new Error('两次输入密码不一致!'));
      } else {
        callback();
      }
    };
    return {
      /**
       * 按钮是否是加载中状态
       */
      loading: false,

      /**
       * registerForm：注册的属性名
       */
      registerForm: {
        /**
         * 数据库中个人或商家用户字段名称由name改成了userName
         */
        userName: '', //用户名称
        password: '', //密码
        checkPassword: '',//检查密码
        telephone: '', //手机号
        email: '', //邮箱
        city: '', //城市
        sex: '0',//性别,默认0,0--男,1--女
        bankCount: '', //银行卡号
        identity: 0, //注册身份,0-用户,1-商家,2-配送员
        account: null, //商家营业执照编号

        /**
         * integral、balance、auditRegistryState、enableState、rate在账户创建时具有一定的初始值
         */
        integral: 0, //积分，由于账户刚刚创建，所以积分默认值是0（100积分=1元）
        balance: 0, //账户余额，由于账户刚刚创建，所以余额默认值是0
        auditRegistryState: 0, //注册状态，由于账户刚刚创建，所以注册状态为：注册未通过 由管理员负责（0：注册并未通过；1：审核已通过；2：审核未通过）
        enableState: 2, //个人/商家用户状态（0：未禁用；1：已禁用；2：注册未审核或审核未通过时没有状态信息）
        rate: 5, //商家等级，由于账户刚刚创建，商家等级默认为5，该字段对个人用户而言无效
      },
      /**
       * 注册验证规则
       */
      registerRules: {
        userName: [{required: true, trigger: 'blur', message: '姓名不能为空'}],
        telephone: [{required: true, trigger: 'blur', message: '电话号码不能为空'},
          {pattern: /^1[3|4|5|7|8][0-9]{9}$/,message: '请输入正确的11位手机号码，第1位是1，第2位是3/4/5/7/8之一，后9位均为0-9之一'}],
        email: [{required: true, trigger: 'blur', message: '邮箱不能为空'},
          {max: 20, pattern: /^\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,message: '请输入正确的邮箱'}],
        bankCount: [{required: true, trigger: 'blur', message: '银行账号不能为空'},
          {pattern: /^([1-9]{1})(\d{15})$/, message: '请输入正确的16位银行卡号', trigger: 'blur'}],
        account: [{required: true, trigger: 'blur', message: '营业执照编号不能为空'},
          {pattern: /^[1-9][0-9]{14}$/, message: '请输入正确的15位营业执照编号'}],
        password: [{required: true, validator: validatePass, trigger: 'blur'},
          {min: 6,max: 12, pattern: /^[A-Za-z][A-Za-z0-9_]{5,12}$/, message: '密码为6-12位，且第1位是字母，后面5-11位是字母数字下划线'}],
        checkPassword: [{required: true, validator: validatePass2, trigger: 'blur'}],
      },
    }
  },
  beforeCreate() {
    $(document).ready(function () {
      window.onload = load2D_bg();
      window.onload = load2D_bg2();
      window.onload = load2D_bg2_2();
      window.onload = load2D_yinghua();
    })
  },
  methods: {
    /**
     * 返回登录页面
     */
    returnLogin() {
      this.$router.push({
        path: "/login"
      })
    },
    /**
     * 重置注册输入框
     */
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    /**
     * 提交注册
     */
    submitForm() {
      this.$refs.refForm.validate(valid => {
        if(this.registerForm.identity===1){
          var random_longitude=Math.ceil(Math.random()*100)/1000;
          var random_latitude=Math.ceil(Math.random()*100)/1000;
          var longitude=116.383141 + random_longitude;
          var latitude=39.913607 + random_latitude;

          const data = {
            userName: this.registerForm.userName,
            password: this.registerForm.password,
            telephone: this.registerForm.telephone,
            email: this.registerForm.email,
            address: this.registerForm.city,
            sex: this.registerForm.sex,
            bankCount: this.registerForm.bankCount,
            identity: this.registerForm.identity,
            account: this.registerForm.account,
            integral: this.registerForm.integral,
            balance: this.registerForm.balance,
            auditRegistryState: this.registerForm.auditRegistryState,
            enableState: this.registerForm.enableState,
            rate: this.registerForm.rate,
            longitude:longitude.toFixed(6),
            latitude:latitude.toFixed(6)
          };

          if (valid) {
            // this.loading = true;
            register(data).then(res => {
              if(res.message===1){
                this.loading = false;
                this.$router.push({
                  path: "/login"
                });
              }else if(res.message==="对不起，此电话号码已经被注册，请重新输入电话号码进行注册") {
                this.loading=false;
                this.$message({
                  message: "对不起，此电话号码已经被注册，请重新输入电话号码进行注册",
                  type: "error"
                })
              }
            }).catch(() => {
              this.loading = false;
            })
          }

        }else{
          const data = {
            userName: this.registerForm.userName,
            password: this.registerForm.password,
            telephone: this.registerForm.telephone,
            email: this.registerForm.email,
            address: this.registerForm.city,
            sex: this.registerForm.sex,
            bankCount: this.registerForm.bankCount,
            identity: this.registerForm.identity,
            account: this.registerForm.account,
            integral: this.registerForm.integral,
            balance: this.registerForm.balance,
            auditRegistryState: this.registerForm.auditRegistryState,
            enableState: this.registerForm.enableState,
            rate: this.registerForm.rate
          };

          if (valid) {
            // this.loading = true;
            register(data).then(res => {
              if(res.message===1){
                this.loading = false;
                this.$router.push({
                  path: "/login"
                });
              }else if(res.message==="对不起，此电话号码已经被注册，请重新输入电话号码进行注册") {
                this.loading=false;
                this.$message({
                  message: "对不起，此电话号码已经被注册，请重新输入电话号码进行注册",
                  type: "error"
                })
              }
            }).catch(() => {
              this.loading = false;
            })
          }
        }
      })
    },

  }
}
</script>

<style lang="less">
.register-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100vh;
}

.form-box {
  width: 600px;
  height: auto;
  opacity: 0.9;
  padding: 15px 30px 20px;
  background: white;
  border-radius: 25px;
}

.form-title {
  margin: 0 auto 35px;
  text-align: center;
  color: #707070;
  font-size: 18px;
  letter-spacing: 2px;
}


div[class="el switch"] {
  padding: 0 0 15px 15px;
}
</style>
